package LiFeedWeb;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import LiFeedWeb.ApplicationManager;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.Element;

/**
 *
 * @author grillo
 */
public class LiFeedController extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            ServletContext servletContext = this.getServletContext();

            String action = request.getParameter("action") != null ? request.getParameter("action") : "";

            if (action.equalsIgnoreCase("logout")) {
                request.getSession().invalidate();
                //session.removeAttribute("openid");
                //session.removeAttribute("openid-claimed");
        	}

            RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/header.jsp");
            requestDispatcher.include(request, response);

            out.println("<div id=\"content\">");

            if(action.equalsIgnoreCase("logout"))
                out.println("<p>Logged out!</p><br/>");
            else {
                if(request.getSession().getAttribute("openid") != null) {
                    String user = request.getParameter("user") != null ? request.getParameter("user") : "";
                    if(user.equals("")) {
                        requestDispatcher = servletContext.getRequestDispatcher("/search.jsp");
                        requestDispatcher.include(request, response);
                    } else {
                        Document dom = ApplicationManager.getInstance().findUserNews(user);

                        if(dom == null)
                            out.println("<p>Errore nell'interrogazione della rete</p><br/><p><a href=\"javascript:history.go(-1);\">Torna alla pagina precedente</a></p>");
                        else {
                            out.println("<h1>ELENCO NEWS DI " + user + "</h1>");
                            out.println("<table id=\"tabella\">");
                            out.println("<th>Titolo</th><th>Link</th><th>Data</th>");
                            if(dom.selectNodes("//favourite_news/news").size() == 0)
                                out.println("<tr><td colspan=\"3\">L'utente non ha nessuna news preferita</td></tr>");
                            else {
                                for(Object el : dom.selectNodes("//favourite_news/news")) {
                                    out.println("<tr><td>" + ((Element)el).attribute("title").getText() + "</td>");
                                    out.println("<td><a href=\"" + ((Element)el).attribute("link").getText() + "\">" + cutLink(((Element)el).attribute("link").getText(), 25) + "</a></td>");
                                    out.println("<td>" + ((Element)el).attribute("pubdate").getText() + "</td></tr>");
                                }
                            }
                            out.println("</table><br/><br/><p><a href=\"javascript:history.go(-1);\">Torna alla pagina precedente</a></p>");
                        }
                    }
                } else {
                    out.println("<p>Effettuare l'accesso con un account OpenId valido per poter fare ricerce sulla rete LiFeed</p><br/>");
                }
            }

            out.println("</div>");

            requestDispatcher = servletContext.getRequestDispatcher("/footer.jsp");
            requestDispatcher.include(request, response);

        } finally {
            out.close();
        }
    }

    private String cutLink(String s, int n) {
        String tmp = s;
        if(tmp.length() > n) {
            tmp = tmp.substring(0,n);
            tmp += "...";
        }
        return tmp;
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}